import { Destroyable, react, reactJson, Event, track, HasOwner, reactJsonWithUndefined } from "xbsj-xe2/dist-node/xe2-base-utils";
import { MyProjectManager } from "../MyProjectManager";
import { Child, TransformedChild } from '@/scripts/dataTypes/interface'
import { getVirtualList, reqQueryBoxByLayer } from '@/api';



export class VirtualLayer extends HasOwner<MyProjectManager> {

    get layerObj() { return this.owner.cimrtsManager.eSRtsTileset }

    // 弹出框事件
    private _dialogEvent = this.dv(new Event<[string]>());
    get dialogEvent() { return this._dialogEvent; }

    // 图层树数组
    private _tranformData = this.dv(reactJson<any>([]));
    get tranformData() { return this._tranformData.value }
    get tranformDataChanged() { return this._tranformData.changed }

    // 获取图层树列表
    async getTreeList() {
        const res = await getVirtualList(this._tileServiceName)
        // @ts-ignore
        if (res.status !== 'ok') return
        const trandata = this.transformChildren(res.data)

        // 获取对象的图层树给 tranformData 中的 color
        setTimeout(() => {

            this.updateTransformDataColors(trandata); // 传入临时数据
            // 最后将处理后的数据赋值
            this._tranformData.value = trandata;
            // console.log(this._tranformData.value,'this._tranformData.value')
        }, 1000)
    }

    async getLayerConfig() {
        const tileServiceName = this._tileServiceName;
        if (!tileServiceName) return;
        const resUrl = `/ts/layer/config/get`;
        if (!tileServiceName) return;
        const authToken = localStorage.getItem('Authorization');
        const requestOptions = {
            headers: {
                ...(authToken ? { 'Authorization': authToken } : {})
            }
        };

        const res = await fetch(`${resUrl}?tileServiceName=${tileServiceName}`, requestOptions);
        const json = await res.text();
        return JSON.parse(json);
    }

    // 修改图层配置
    async saveLayerConfig() {
        const tileServiceName = this._tileServiceName;
        if (!tileServiceName) return;
        const resUrl = `/ts/layer/config/put`;
        const authToken = localStorage.getItem('Authorization');
        const layerConfig = this.owner.cimrtsManager.eSRtsTileset.layerConfig ?? {};
        const requestOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...(authToken ? { 'Authorization': authToken } : {})
            },
            body: JSON.stringify({
                tileServiceName: tileServiceName,
                layerConfig: JSON.stringify(layerConfig)
            })
        };

        const res = await fetch(resUrl, requestOptions);
        const json = await res.json();
        return json;
    }


    /**递归children，过滤字段*/
    transformChildren(children: Child[]): TransformedChild[] {
        if (Array.isArray(children)) {
            return children.map(child => ({
                label: child.layerName,
                value: child.index,
                id: child.id,
                children: child.children ? this.transformChildren(child.children) : []
            }));
        }
        return [];
    }

    // 根据图层获取其下所有要素的范围
    async queryBoxByLayer(layerId: string) {
        try {
            const data = {
                "tileServiceName": this._tileServiceName,
                "layerId": layerId
            }
            const res = await reqQueryBoxByLayer(data)
            // @ts-ignore
            if (res.status != 'ok') return;
            const { boundingbox, lonLatboundingbox } = res.data
            return {
                radius: boundingbox.sphereRadius * 3 + boundingbox.maxZ,
                rectangle: [lonLatboundingbox.minX, lonLatboundingbox.minY, lonLatboundingbox.maxX, lonLatboundingbox.maxY]
            }
        } catch (error) {
            console.error(error)
        }

    }


    /**更新 tranformData 中的颜色*/
    updateTransformDataColors(data: TransformedChild[]) {
        const layerConfig = this.layerObj.layerConfig;
        const updateColors = (data: any[]) => {
            data.forEach(item => {
                // 查找匹配的 layerConfig
                if (!layerConfig) return;
                const config = layerConfig[item.value];
                // 如果存在对应的 layerConfig，更新颜色
                if (config && Object.keys(config).length > 0) {
                    item.color = config.color; // 更新颜色
                    item.visible = config.visible; // 更新选中状态
                } else {
                    // 如果不存在对应的 layerConfig，设置默认值
                    item.color = '#FFFFFF'; // 更新颜色
                    item.visible = true; // 更新选中状态
                }
                // 递归处理子节点
                if (item.children && item.children.length > 0) {
                    updateColors(item.children);
                }
            });
        };
        updateColors(data);
    }

    async init() {
        await this.getTreeList()
    }
    constructor(private _tileServiceName: string, owner: MyProjectManager) {
        super(owner);
    }
}















